import tools from '@/utils/tools'
/* get currentAgencies */
export const getCurrentAgencies = () => {
    let agency = tools.getCookie('currentAgencies')
    return agency ? JSON.parse(agency) : ''
}
/* set currentAgencies */
export const setCurrentAgencies = (agencies) => {
    let agency = JSON.stringify(agencies)
    return tools.setCookie('currentAgencies', agency)
}
/* delete currentAgencies */
export const removeCurrentAgencies = () => {
    return tools.deletCookie('currentAgencies')
}
/* 获得当前选中的机构（多用于 Grantee 角色） */
export const getSelectedAgency = () => {
    let agency = sessionStorage.getItem('selectedAgency')
    return agency ? JSON.parse(agency) : ''
}
/* 设置当前选中的机构（多用于 Grantee 角色） */
export const setSelectedAgency = (newSelectAgency) => {
    let agency = JSON.stringify(newSelectAgency)
    return sessionStorage.setItem('selectedAgency', agency)
}
/* get currentUser from cookie */
export const getCurrentUser = () => {
    let user = null
    var cookie = tools.getCookie('currentUser')
    var agenciesCookie = tools.getCookie('currentAgencies')
    try {
        user = JSON.parse(cookie)
        let agencies = JSON.parse(agenciesCookie)
        Object.assign(user, agencies)
    } catch (e) {
        try {
            user = cookie
            Object.assign(user, agenciesCookie)
        } catch (e) {
            return null
        }
    }
    // if (user && user.userInfo && user.userInfo.lastName) {
    //     user.userInfo.displayName = user.userInfo.lastName
    // }
    return user
}

export const isTeacher = () => {
    const role = store.state.user.currentUser.role
    var isTeacher = (role.toUpperCase() !== UserRole['AGENCY_ADMIN'] && role.toUpperCase() !== UserRole['SITE_ADMIN'] && role.toUpperCase() !== UserRole['AGENCY_OWNER'])
    return isTeacher
}

/* set currentUser */
export const setCurrentUser = (newUser) => {
    if (!newUser) {
        tools.deletCookie('currentUser')
        tools.deletCookie('currentAgencies')
        return
    }
    let user = Object.assign({}, newUser)
    user.currentAgencyId = user.defaultAgencyId
    var tempAgencies = {
        agencies: user.agencies
    }
    delete user.agencies

    let currentUser = JSON.stringify(user)
    let currentUserAgencies = JSON.stringify(tempAgencies)
    tools.setCookie('currentAgencies', currentUserAgencies)
    return tools.setCookie('currentUser', currentUser)
}
/* delete currentUser */
export const removeCurrentUser = () => {
    return tools.deletCookie('currentUser')
}
/* the currentUser is login or not */
export const isAuthenticated = () => {
    if (getCurrentUser() && getCurrentUser() !== 'null') {
        return true
    }
    return false
}

/* across role */
export const acrossRole = (...values) => {
    if (!values.length) {
        return false
    }
    if (!isAuthenticated()) {
        return
    }
    let role = getCurrentUser().role.toUpperCase()
    for (let val of values) {
        if (val.toUpperCase() === role) {
            return true
        }
    }
}


export const toDecimal = (value) => {
    return Math.round(value * 100) / 100
}

export const getFileSize = (size) => {
    var result = ''
    size = parseInt(size)
    if (isNaN(size)) {
        result = 0 + 'K'
    } else if (size < 1024 * 500) {
        result = toDecimal(size / 1024) + 'K'
    } else {
        result = toDecimal(size / (1024 * 1024)) + 'M'
    }
    return result
}

export const minPeriodDays = 15
export const maxPeriodDays = 300
// from underscore isEqual
export const deepEqual = (a, b) => {
    let isFunction, has, eq, deepEq
    isFunction = function (obj) {
        return typeof obj === 'function' || false
    }
    has = function (obj, path) {
        return obj != null && Object.prototype.hasOwnProperty.call(obj, path)
    }
    eq = function (a, b, aStack, bStack) {
        // Identical objects are equal. `0 === -0`, but they aren't identical.
        // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
        if (a === b) return a !== 0 || 1 / a === 1 / b
        // `null` or `undefined` only equal to itself (strict comparison).
        if (a == null || b == null) return false
        // `NaN`s are equivalent, but non-reflexive.
        if (a !== a) return b !== b
        // Exhaust primitive checks
        let type = typeof a
        if (type !== 'function' && type !== 'object' && typeof b != 'object') return false
        return deepEq(a, b, aStack, bStack)
    }

    // Internal recursive comparison function for `isEqual`.
    deepEq = function (a, b, aStack, bStack) {
        // Compare `[[Class]]` names.
        let className = Object.prototype.toString.call(a)
        if (className !== Object.prototype.toString.call(b)) return false
        switch (className) {
            // Strings, numbers, regular expressions, dates, and booleans are compared by value.
            case '[object RegExp]':
            // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
            case '[object String]':
                // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
                // equivalent to `new String("5")`.
                return '' + a === '' + b
            case '[object Number]':
                // `NaN`s are equivalent, but non-reflexive.
                // Object(NaN) is equivalent to NaN.
                if (+a !== +a) return +b !== +b
                // An `egal` comparison is performed for other numeric values.
                return +a === 0 ? 1 / +a === 1 / b : +a === +b
            case '[object Date]':
            case '[object Boolean]':
                // Coerce dates and booleans to numeric primitive values. Dates are compared by their
                // millisecond representations. Note that invalid dates with millisecond representations
                // of `NaN` are not equivalent.
                return +a === +b
            case '[object Symbol]':
                return Symbol.prototype.valueOf.call(a) === Symbol.prototype.valueOf.call(b)
        }

        let areArrays = className === '[object Array]'
        if (!areArrays) {
            if (typeof a != 'object' || typeof b != 'object') return false

            // Objects with different constructors are not equivalent, but `Object`s or `Array`s
            // from different frames are.
            let aCtor = a.constructor;
            let bCtor = b.constructor
            if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor &&
                    isFunction(bCtor) && bCtor instanceof bCtor) &&
                ('constructor' in a && 'constructor' in b)) {
                return false
            }
        }
        // Assume equality for cyclic structures. The algorithm for detecting cyclic
        // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.

        // Initializing stack of traversed objects.
        // It's done here since we only need them for objects and arrays comparison.
        aStack = aStack || []
        bStack = bStack || []
        let length = aStack.length
        while (length--) {
            // Linear search. Performance is inversely proportional to the number of
            // unique nested structures.
            if (aStack[length] === a) return bStack[length] === b
        }

        // Add the first object to the stack of traversed objects.
        aStack.push(a)
        bStack.push(b)

        // Recursively compare objects and arrays.
        if (areArrays) {
            // Compare array lengths to determine if a deep comparison is necessary.
            length = a.length
            if (length !== b.length) return false
            // Deep compare the contents, ignoring non-numeric properties.
            while (length--) {
                if (!eq(a[length], b[length], aStack, bStack)) return false
            }
        } else {
            // Deep compare objects.
            let keys = Object.keys(a);
            let key
            length = keys.length
            // Ensure that both objects contain the same number of properties before comparing deep equality.
            if (Object.keys(b).length !== length) return false
            while (length--) {
                // Deep compare each member
                key = keys[length]
                if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) return false
            }
        }
        // Remove the first object from the stack of traversed objects.
        aStack.pop()
        bStack.pop()
        return true
    }

    // Perform a deep comparison to check if two objects are equal.
    return eq(a, b)
}
